package com.example.shardingjdbc.sharding.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @Description: 精准分库算法
 * @Author: Jerry
 * @Date: 2021-07-14 23:43
 */
public class DBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
    /**
     * tableNames 对应分片库中所有分片表的集合
     * shardingValue 为分片属性，其中 logicTableName 为逻辑表，columnName 分片健（字段），value 为从 SQL 中解析出的分片健的值
     */
    @Override
    public String doSharding(Collection<String> databaseList, PreciseShardingValue<Long> shardingValue) {
        for (String database: databaseList) {
            String userIdLastValue = String.valueOf(shardingValue.getValue());
            int userIdLength = userIdLastValue.length();
            int value =
                    Integer.parseInt(userIdLastValue.substring(userIdLength - 2, userIdLength - 1)) % databaseList.size();

            if (database.endsWith(String.valueOf(value))) {
                return database;
            }
        }
        throw new IllegalArgumentException();
    }
}
